package com.maixun.uitrasound.splash

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.maixun.lib_base.utils.LogUtils
import com.maixun.lib_comment.ARouterConstance
import com.maixun.lib_comment.SharedPrefConstance
import com.maixun.lib_base.utils.SharedPrefUtil
import com.maixun.lib_comment.CommentApplication
import com.maixun.lib_comment.ui.BaseMVPActivity
import com.maixun.uitrasound.R
import com.maixun.uitrasound.ad.ADFragment
import com.maixun.uitrasound.entity.BannerBeen
import java.util.*

/**
 * @author：Lmoumou
 * @date：2020/10/14
 */
class SplashActivity:BaseMVPActivity<SplashPresenterImpl>(),SplashContract.View {

    companion object {
        fun startThis(context: Context) {
            context.startActivity(Intent(context.applicationContext, SplashActivity::class.java))
        }
    }

    override val mPresenter: SplashPresenterImpl by lazy { SplashPresenterImpl(this) }

    override fun getLayoutId(): Int = R.layout.activity_splash

    override fun initView(savedInstanceState: Bundle?) {
        mPresenter.pSplashAD()
        val jsonStr = SharedPrefUtil.open(SharedPrefConstance.AD.NAME)
            .getString(SharedPrefConstance.AD.DATA_KEY)
        val dataList = Gson().fromJson<MutableList<BannerBeen>>(
            jsonStr,
            object : TypeToken<MutableList<BannerBeen>>() {}.type
        )
        if (dataList.isNullOrEmpty()) {
            toMain(2000)
        } else {
            toAD(dataList)
        }
    }

    override fun vSplashAD(result: MutableList<BannerBeen>?) {
        LogUtils.e("LLLLL","result->${result}")
        //将现在的数据替换之前的数据
        SharedPrefUtil.open(SharedPrefConstance.AD.NAME).remove(SharedPrefConstance.AD.DATA_KEY)
        val toJson = Gson().toJson(result)
        SharedPrefUtil.open(SharedPrefConstance.AD.NAME)
            .putString(SharedPrefConstance.AD.DATA_KEY, toJson)
        if (result != null && result.isNotEmpty()) {
            result.forEach {
                Glide.with(CommentApplication.mContext).load(it.url).submit()
            }
        }
    }
    private val handler by lazy { Handler() }
    /**
     * 等待1秒后调转到MainActivity
     * */
    private fun toMain(delay: Long) {
        handler.postDelayed({
            ARouter.getInstance().build(ARouterConstance.APP.URL_MAIN).navigation()
            finish()
        }, delay)
    }

    private fun toAD(result: MutableList<BannerBeen>) {
        val selectData = selectByWeight(result)

        val fragment = ADFragment.newInstance(selectData)

        supportFragmentManager
            .beginTransaction()
            .setCustomAnimations(
                R.anim.login_anim_fade_in,
                R.anim.login_anim_fade_out,
                R.anim.login_anim_fade_in,
                R.anim.login_anim_fade_out
            )
            .replace(R.id.flContent, fragment)
            .addToBackStack(null)
            .commit()
    }

    private fun selectByWeight(result: MutableList<BannerBeen>): BannerBeen {
        val random = Random()
        var allWeight = 0
        result.forEach {
            allWeight += it.weight
        }
        if (allWeight == 0) return result[0]
        val n = random.nextInt(allWeight)
        var m = 0
        result.forEachIndexed { _, bannerBeen ->
            if (m <= n && n < (m + bannerBeen.weight)) {
                return bannerBeen
            }
            m += bannerBeen.weight
        }
        return result[0]
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
}